package com.zhaosc.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class NettyClientInHandler extends ChannelInboundHandlerAdapter {

	private StringBuffer message;
	
	private String sendMsg;
	
	
	public NettyClientInHandler(StringBuffer message, String sendMsg) {
		super();
		this.message = message;
		this.sendMsg = sendMsg;
	}


	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		 System.out.println("***********channelActive**********");
		 
		 ByteBuf encoded=ctx.alloc().buffer(4*sendMsg.length());
		 encoded.writeBytes(sendMsg.getBytes());
		 ctx.write(encoded);
		 ctx.flush();
	}


	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		System.out.println("***********chanelRead************");
		ByteBuf result=(ByteBuf)msg;
		
		byte[] result1=new byte[result.readableBytes()];
		result.readBytes(result1);
		System.out.println("********server response msg*************");
		message.append(new String(result1));
		result.release();
		
	}

	

}
